package com.gmlive.gradle.versionlint.repositories

import com.gmlive.gradle.versionlint.extensions.firstReleaseVersion
import com.gmlive.gradle.versionlint.library.Library
import com.google.gson.Gson
import okhttp3.*

internal class InkeRepository(client: OkHttpClient) : MavenRemoteRepository(client) {

    private data class InkeResponse(val result: InkeResponseResult)

    private data class InkeResponseResult(val data: MutableList<InkeResponseDataItem>)

    private data class InkeResponseDataItem(val version: String)


    override fun getNewVersionOrNull(
        actualLibrary: Library,
        responseBody: String
    ): RepositoryResult = try {

        val inkeResponse = Gson().fromJson(responseBody, InkeResponse::class.java)
        val responseVersions = inkeResponse.result.data

        if (responseVersions.isEmpty()) {
            RepositoryResult.ArtifactNotFound
        } else {
            val releaseVersion =
                responseVersions.map { version -> version.version }.firstReleaseVersion()
            when {
                releaseVersion == actualLibrary.version -> RepositoryResult.NoUpdateFound
                releaseVersion != null -> {
                    RepositoryResult.NewVersionAvailable(
                        actualLibrary.copy(version = releaseVersion)
                    )
                }
                else -> RepositoryResult.ArtifactNotFound
            }
        }
    } catch (e: Throwable) {
        println("${actualLibrary.artifactId} can not find new version throw by exception")
        RepositoryResult.ArtifactNotFound
    }

    override fun createQueryFromLibrary(library: Library): Request {
        val query = StringBuilder()
            .append("https://repository.inkept.cn/service/extdirect")
        return Request
            .Builder()
            .header("Content-Type", "application/json;charset=utf-8")
            .url(query.toString())
            .post(
                RequestBody.create(
                    MediaType.parse("application/json"),
                    InkeRepositoryRequestBody().apply {
                        data.add(InkeRepositoryDataItem().apply {
                            sort.add(InkeRepositorySortItem())
                            filter.add(InkeRepositoryFilterItem("format", "maven2"))
                            filter.add(
                                InkeRepositoryFilterItem(
                                    "attributes.maven2.groupId",
                                    library.groupId
                                )
                            )
                            filter.add(
                                InkeRepositoryFilterItem(
                                    "attributes.maven2.artifactId",
                                    library.artifactId
                                )
                            )
                        })

                    }.toString()
                )
            )
            .build()
    }
}

private data class InkeRepositoryRequestBody(
    val action: String = "coreui_Search",
    val method: String = "read",
    val type: String = "rpc",
    val tid: Int = 6,
    val data: MutableList<InkeRepositoryDataItem> = mutableListOf()
){
    override fun toString(): String {
        return Gson().toJson(this)
    }
}


private data class InkeRepositoryDataItem(
    val page: Int = 1,
    val start: Int = 0,
    val limit: Int = 20,
    val sort: MutableList<InkeRepositorySortItem> = mutableListOf(),
    val filter: MutableList<InkeRepositoryFilterItem> = mutableListOf()
){
    override fun toString(): String {
        return Gson().toJson(this)
    }
}


private data class InkeRepositorySortItem(
    val property: String = "version",
    val direction: String = "DESC"
){
    override fun toString(): String {
        return Gson().toJson(this)
    }
}


private data class InkeRepositoryFilterItem(
    val property: String = "version",
    val value: String = "DESC"
){
    override fun toString(): String {
        return Gson().toJson(this)
    }
}



